/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package view;

import HibernateConfig.HibernateUtil;
import java.io.FileInputStream; 
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.sql.SQLException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import model.ConexionReporte;
import model.ReporteSimulacion;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;
import static net.sf.jasperreports.engine.util.JRResourcesUtil.getClassLoader;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
/**
 *sss
 * @author core i5
 */
public class Reporte extends javax.swing.JDialog {

    Map combo;
    /**
     * Creates new form Reporte
     */
    public Reporte(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        Date factual=new Date();
        this.dateDesde.setDate(factual);
        this.dateHasta.setDate(factual);
        this.dateDesde.getDateEditor().setEnabled(false);
        this.dateHasta.getDateEditor().setEnabled(false);
    }

    Reporte() throws SQLException{
        initComponents(); //To change body of generated methods, choose Tools | Templates.
        Date factual=new Date();
        this.dateDesde.setDate(factual);
        this.dateHasta.setDate(factual);
        this.dateDesde.getDateEditor().setEnabled(false);
        this.dateHasta.getDateEditor().setEnabled(false);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        btnIniciar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        dateDesde = new com.toedter.calendar.JDateChooser();
        dateHasta = new com.toedter.calendar.JDateChooser();
        comboFecha = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Reporte");
        setResizable(false);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Criterios"));
        jPanel1.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N

        btnIniciar.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        btnIniciar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/Play.png"))); // NOI18N
        btnIniciar.setText("Generar");
        btnIniciar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnIniciarMouseClicked(evt);
            }
        });
        btnIniciar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnIniciarActionPerformed(evt);
            }
        });

        btnCancelar.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/Cancelar.png"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnCancelarMouseClicked(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        jLabel2.setText("Desde:");

        jLabel3.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        jLabel3.setText("Hasta:");

        dateDesde.setToolTipText("");
        dateDesde.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                dateDesdePropertyChange(evt);
            }
        });
        dateDesde.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                dateDesdeKeyTyped(evt);
            }
        });

        dateHasta.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                dateHastaPropertyChange(evt);
            }
        });

        comboFecha.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Todos" }));

        jLabel1.setText("Seleccionar simulación dentro del rango:");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addComponent(jLabel2)
                .addGap(10, 10, 10)
                .addComponent(dateDesde, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(60, 60, 60)
                .addComponent(jLabel3)
                .addGap(18, 18, 18)
                .addComponent(dateHasta, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(comboFecha, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(65, 65, 65)
                .addComponent(btnIniciar, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(96, 96, 96)
                .addComponent(btnCancelar))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(37, 37, 37)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(dateDesde, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(dateHasta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(45, 45, 45)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(comboFecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(53, 53, 53)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnIniciar)
                    .addComponent(btnCancelar)))
        );

        dateDesde.getAccessibleContext().setAccessibleName("");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        setSize(new java.awt.Dimension(482, 320));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void btnIniciarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnIniciarMouseClicked

        int dialogButton = JOptionPane.YES_NO_OPTION;
        int dialogResult = JOptionPane.showConfirmDialog (null, "¿Desea generar el reporte?","Confirmación",dialogButton);
        if(dialogResult == JOptionPane.YES_OPTION){try {
            if(dateDesde.getDate().compareTo(dateHasta.getDate())>0){
              JOptionPane.showMessageDialog(null, "La fecha de desde debe ser menor que la fecha de Hasta");
            }
            else{
                InputStream inputStream = null;
                // si el usuario eligio "SI"
                ConexionReporte con= new ConexionReporte();
                con.SetearConexion();
                String simuquery="-1";
                Integer idsimu=0;
                if (!comboFecha.getSelectedItem().toString().equals("Todos")){
                   idsimu=Integer.parseInt(comboFecha.getSelectedItem().toString());
                }
                SimpleDateFormat dt = new SimpleDateFormat("dd/MM/yyyy");
                String fechaDesde = dt.format(dateDesde.getDate()) + " 00:00";
                String fechaHasta = dt.format(dateHasta.getDate()) + " 23:59";
              //  String filePath = System.getProperty("user.dir") + System.getProperty("file.separator")
                //        + "src"+ System.getProperty("file.separator")+ "view" + System.getProperty("file.separator")
                  //      + "reportesimulacion.jasper";
                URL url = ClassLoader.getSystemResource("view/reportesimulacion.jasper");
                String rutita="";
                try {
                    rutita = url.toURI().toString();
                } catch (URISyntaxException ex) {
                    Logger.getLogger(Reporte.class.getName()).log(Level.SEVERE, null, ex);
                }
                String filePath2=rutita.replace("%20", " ");
                String filePath=filePath2.replace("file:/", "");

                Map params = new HashMap();
                params.put("fechaDesde", fechaDesde);
                params.put("fechaHasta", fechaHasta);
                params.put("reporteruta", filePath);
                if (!comboFecha.getSelectedItem().toString().equals("Todos")){
                   // simuquery=" AND ReporteSimulacion."+'"'+"id_reportesimulacion"+'"'+"="+idsimu+" ";
                    simuquery=idsimu+"";
                }
                params.put("querysimu", simuquery);
                // JasperReport jasperReport = (JasperReport) JRLoader.loadObject(inputStream);
                JasperReport jasperReport=null;
                try {
                    jasperReport = (JasperReport) JRLoader.loadObject(url);
                } catch (JRException ex) {
                    //Registro LOG

                    System.out.println(ex.toString());
                }
                JasperPrint jasperPrint = null; 
                try {
                    jasperPrint = JasperFillManager.fillReport(jasperReport, params, con.getCon());
                } catch (JRException ex) {
                    System.out.println(ex.toString());
                }
                JDialog dialog = new JDialog(this, true);
                dialog.getContentPane().add(new net.sf.jasperreports.view.JRViewer(jasperPrint));
                dialog.pack();
                dialog.setSize(800, 600);
                dialog.setLocationRelativeTo(null);
                dialog.setVisible(true);
                    
                }
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(Reporte.class.getName()).log(Level.SEVERE, null, ex);
            }
          } 
    }//GEN-LAST:event_btnIniciarMouseClicked

    private void btnIniciarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnIniciarActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_btnIniciarActionPerformed

    private void btnCancelarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnCancelarMouseClicked

        this.dispose();
        new Menu().setVisible(true);
    }//GEN-LAST:event_btnCancelarMouseClicked

    private void dateDesdeKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_dateDesdeKeyTyped
        evt.consume();// TODO add your handling code here:
    }//GEN-LAST:event_dateDesdeKeyTyped

    private void dateDesdePropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_dateDesdePropertyChange
        ReporteSimulacion simutemp;
        combo= new HashMap<Integer,String>();
        comboFecha.removeAllItems();
        this.comboFecha.addItem("Todos");
        if((dateHasta.getDate()!=null)&&(dateDesde.getDate()!=null)&&(dateDesde.getDate().compareTo(dateHasta.getDate())<=0)){
        Session sesion = HibernateUtil.getSessionFactory().openSession();
        Transaction transaccion=null;
        SimpleDateFormat dt = new SimpleDateFormat("dd/MM/yyyy");
        String frmDate = dt.format(dateDesde.getDate()) + " 00:00";
        String enDate = dt.format(dateHasta.getDate()) + " 23:59";
        try{
            transaccion = sesion.beginTransaction();
            String hql = "FROM ReporteSimulacion r WHERE ";
            
             hql=hql.concat("r.fechaInicioSim BETWEEN :stDate AND :edDate");
             
             List paquetes = sesion.createQuery(hql).setParameter("stDate", frmDate).setParameter("edDate", enDate).list();   // query para obtener los paquetes
            Iterator iterador = paquetes.iterator();
            
            while (iterador.hasNext()){
                simutemp = (ReporteSimulacion) iterador.next();
                Integer tamini=combo.size();
                combo.put(simutemp.getIdReportesimulacion(),"Presente");
                if(combo.size()>tamini){
                   this.comboFecha.addItem(""+simutemp.getIdReportesimulacion());
                }
            }
            combo.clear();
        }catch (HibernateException ex){
                    transaccion.rollback();
                    System.err.println("Got an exception! ");
                    System.err.println(ex.getMessage());
        }finally {
           sesion.close(); // cierro la sesion (BD)
        }
        }// TODO add your handling code here:
    }//GEN-LAST:event_dateDesdePropertyChange

    private void dateHastaPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_dateHastaPropertyChange
        ReporteSimulacion simutemp;
        combo= new HashMap<Integer,String>();
        comboFecha.removeAllItems();
        this.comboFecha.addItem("Todos");
        if((dateHasta.getDate()!=null)&&(dateDesde.getDate()!=null)&&(dateDesde.getDate().compareTo(dateHasta.getDate())<=0)){
        Session sesion = HibernateUtil.getSessionFactory().openSession();
        Transaction transaccion=null;
        SimpleDateFormat dt = new SimpleDateFormat("dd/MM/yyyy");
        String frmDate = dt.format(dateDesde.getDate()) + " 00:00";
        String enDate = dt.format(dateHasta.getDate()) + " 23:59";
        try{
            transaccion = sesion.beginTransaction();
            String hql = "FROM ReporteSimulacion r WHERE ";
            
             hql=hql.concat("r.fechaInicioSim BETWEEN :stDate AND :edDate");
             
             List paquetes = sesion.createQuery(hql).setParameter("stDate", frmDate).setParameter("edDate", enDate).list();   // query para obtener los paquetes
            Iterator iterador = paquetes.iterator();
            
            while (iterador.hasNext()){
                simutemp = (ReporteSimulacion) iterador.next();
                Integer tamini=combo.size();
                combo.put(simutemp.getIdReportesimulacion(),"Presente");
                if(combo.size()>tamini){
                   this.comboFecha.addItem(""+simutemp.getIdReportesimulacion());
                }
            }
            combo.clear();
        }catch (HibernateException ex){
                    transaccion.rollback();
                    System.err.println("Got an exception! ");
                    System.err.println(ex.getMessage());
        }finally {
           sesion.close(); // cierro la sesion (BD)
        }
        }// TODO add your handling code here:
    }//GEN-LAST:event_dateHastaPropertyChange

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Reporte.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Reporte.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Reporte.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Reporte.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    new Reporte().setVisible(true);
                } catch (SQLException ex) {
                    Logger.getLogger(Reporte.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnIniciar;
    private javax.swing.JComboBox comboFecha;
    private com.toedter.calendar.JDateChooser dateDesde;
    private com.toedter.calendar.JDateChooser dateHasta;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    // End of variables declaration//GEN-END:variables
}
